//
//  WJScaleFadeAnimator.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/28.
//

import UIKit

class WJScaleFadeAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    
    // 标记是呈现（Present）还是消失（Dismiss）
    let isPresenting: Bool
    
    init(isPresenting: Bool) {
        self.isPresenting = isPresenting
        super.init()
    }
    
    // 动画持续时间
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.4
    }
    
    // 执行动画的核心方法
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let containerView = transitionContext.containerView
        
        if isPresenting {
            // 呈现动画
            guard let toViewController = transitionContext.viewController(forKey: .to),
                  let toView = transitionContext.view(forKey: .to) else {
                transitionContext.completeTransition(false)
                return
            }
            
            // 将目标视图添加到容器
            containerView.addSubview(toView)
            
            // 设置目标视图的frame
            toView.frame = transitionContext.finalFrame(for: toViewController)
            
            // 设置初始状态：缩小并透明
            toView.alpha = 0.0
            toView.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
            
            // 执行动画到最终状态：正常大小，不透明
            UIView.animate(
                withDuration: transitionDuration(using: transitionContext),
                delay: 0,
                usingSpringWithDamping: 0.7,
                initialSpringVelocity: 0.3,
                options: .curveEaseInOut
            ) {
                toView.alpha = 1.0
                toView.transform = .identity
            } completion: { finished in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        } else {
            // 消失动画
            guard let fromView = transitionContext.view(forKey: .from) else {
                transitionContext.completeTransition(false)
                return
            }
            
            UIView.animate(
                withDuration: transitionDuration(using: transitionContext),
                animations: {
                    fromView.alpha = 0.0
                    fromView.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
                },
                completion: { finished in
                    fromView.removeFromSuperview()
                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
                }
            )
        }
    }
}
